<template>
	<div>
		<div class="font-size18 font-bold margin-bottom20 color252630">视频管理</div>
		<el-form inline :model="query" label-width="80">
			<el-form-item label="模糊搜索">
				<el-input placeholder="请输入关键字" v-model="query.title" class="width260 margin-right30"></el-input>
			</el-form-item>
			<el-form-item label="视频分类">
				<el-select v-model="query.sort" class="width260" clearable>
					<el-option v-for="point in sorts" :key="point.id" :label="point.name" :value="point.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-button type="primary" icon="el-icon-search" class="margin-left10" @click="handleSearch">搜索</el-button>
			<el-button type="default" icon="el-icon-refresh-right" @click="handleRefresh">重置</el-button>
		</el-form>
		<div class=" row-me">
			<el-button type="primary">批量删除</el-button>
			<el-button type="primary" @click="handleAdd">新增视频</el-button>
			<el-button @click="tencentVisible=true">腾讯云点播设置</el-button>
			<div class="flex1"></div>
			<el-button type="primary" @click="videoVisible=true">视频分类</el-button>
		</div>
		<el-table :data="tableData" border class="margin-top20" header-cell-class-name="table-header-style"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center"></el-table-column>
			<el-table-column prop="id" label="ID" align="center" width="80"></el-table-column>
			<el-table-column label="缩略图（点击放大）" width="200">
				<template slot-scope="scope">
					<el-image style="max-height: 50px; max-width: 50px; width: auto" class="table-td-thumb"
						:src="scope.row.thumbnail" :preview-src-list="[scope.row.thumbnail]"></el-image>
				</template>
			</el-table-column>
			<el-table-column prop="title" label="视频信息" :show-overflow-tooltip="true" width="500">
			</el-table-column>
			<el-table-column prop="duration" label="视频时长" align="center"></el-table-column>
			<el-table-column prop="fileSize" label="视频大小" align="center" width="100"></el-table-column>
			<el-table-column label="视频分类" align="center" width="200" prop="sortName"></el-table-column>
			<el-table-column prop="createTime" label="上传时间" align="center" width="160"></el-table-column>
			<el-table-column prop="url" label="视频地址" align="center" width="100">
				<template slot-scope="scope">
					<a :href="scope.row.url" target="_blank" class="blue-text">点击查看</a>
				</template>
			</el-table-column>
			<el-table-column prop="id" label="二维码" align="center">
				<template slot-scope="scope">
					<el-button type="text" @click="lookQrcode(scope.row)">点击查看</el-button>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" width="160" fixed="right">
				<template slot-scope="scope">
					<el-button type="text" @click="handleAdd(scope.row)">编辑</el-button>
					<el-popconfirm title="确认删除？" @confirm="handleDel(scope.row.id)">
						<el-button slot="reference" type="text">删除</el-button>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
		<div class="margin-top10">
			<el-pagination background layout="->,total,sizes, prev, pager, next" :current-page="query.pageNumber"
				:page-sizes="[30, 40, 50, 60]" @size-change="handleSizeChange" :page-size="query.pageSize" :total="pageTotal"
				@current-change="handlePageChange"></el-pagination>
		</div>

		<!-- 新增修改视频 -->
		<el-dialog :title="title" :visible.sync="editVisible" width="50%">
			<el-form :model="form" ref="form" label-width="100px" :rules="rules">
				<el-form-item label="视频标题" prop="title">
					<el-input v-model="form.title" placeholder="请输入视频标题" class="width500"></el-input>
				</el-form-item>
				<el-form-item label="视频分类" prop="sort">
					<el-select filterable v-model="form.sort" placeholder="请选择视频分类" :clearable="true" class="width500">
						<el-option v-for="point in sorts" :key="point.id" :label="point.name" :value="point.id+''">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上传缩略图" prop="thumbnail">
					<el-image v-if="form.thumbnail" class="width100 height100 radius6 margin-right10" :src="form.thumbnail"
						:preview-src-list="[form.thumbnail]"></el-image>
					<el-button type="text" @click="clickImg">点击图片库</el-button>
				</el-form-item>
				<el-form-item label="视频上传" prop="url">
					<template>
						<div class="upload_video" id="upload_video">
							<el-upload class="upload-demos" ref="upload" action="#" :http-request="uploadVideo" :limit="1"
								:on-change="handleChange" accept=".mp4">
								<el-button size="small" type="primary">点击上传</el-button>
								<el-progress class="progress" :text-inside="true" :stroke-width="18" :percentage="progress"
									status="exception" v-if="progress"></el-progress>
								<div slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过500M</div>
							</el-upload>
							<video v-if="form.url" :src="form.url" id="video" width="400px" height="300px" controls></video>
							<img id="video_img" style="width:90px;height:160px;display:none">
						</div>
					</template>
				</el-form-item>
				<el-form-item label="视频链接">
					<el-input v-model="form.url" placeholder="请输入视频链接" class="width500"></el-input>
				</el-form-item>
				<el-form-item label="视频描述">
					<el-input v-model="form.description" placeholder="请输入视频描述" class="width500">
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitQuestionVideo">立即提交</el-button>
					<el-button @click="editVisible = false">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<!-- 视频分类 -->
		<el-dialog title="视频分类" :visible.sync="videoVisible" width="50%" @close="handleClose">
			<videoCategory :type="1"></videoCategory>
			<span slot="footer">
				<el-button type="primary" @click="videoVisible=false">关 闭</el-button>
			</span>
		</el-dialog>

		<!-- 腾讯云点播设置 -->
		<el-dialog title="腾讯云点播设置" :visible.sync="tencentVisible" width="40%">
			<div class="row-me row-center">
				<span class="width160 font-size14">腾讯云点播设置：</span>
				<el-input type="text" v-model="vodSubAppid"></el-input>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="tencentVisible = false">取 消</el-button>
				<el-button type="primary" @click="vodChange">确 定</el-button>
			</span>
		</el-dialog>

		<el-dialog title="二维码" :visible.sync="qrcodeVisible" width="40%">
			<div class="column-me center-all font-size16">
				<div class="row-me margin-top20">
					<div class="shijuan">
						App二维码 ：
					</div>
					<div>
						<div class="row-me flex-end2">
							<div id="qrCode" class="margin-top10 ">
								<div id="code" ref="appQrCodeUrl" title="" align="center"></div>
							</div>
							<span class="margin-left10" @click="handleDownloadAppQrIMg"> <i
									class="el-icon-download"></i>点击下载二维码</span>
						</div>
					</div>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="qrcodeVisible = false">关闭</el-button>
			</span>
		</el-dialog>

		<imgLibrary ref="imgLibrary" @handleImgOk="handleImgOk"></imgLibrary>
	</div>
</template>

<script>
	import videoCategory from "@/components/videoCategory"
	import TcVod from 'vod-js-sdk-v6'
	import imgLibrary from "@/components/imgLibrary"
	import QRCode from 'qrcodejs2';
	export default {
		components: {
			videoCategory,
			imgLibrary
		},
		data() {
			return {
				query: {
					pageNumber: 1,
					pageSize: 30
				},
				pageTotal: 0,
				tableData: [],
				multipleSelection: [],
				editVisible: false,
				title: '',
				form: {},
				sorts: [],
				fileList: [],
				// 进度条百分比
				progress: 0,
				uploadUrl: this.$host + '/file/upload?token=' + localStorage.getItem('token'),
				fileList: [],
				videoVisible: false,
				videoFileList: [],
				tencentVisible: false,
				vodSubAppid: '',
				vodId: '',
				qrcodeVisible: false,
				rules: {
					title: {
						required: true,
						message: '请输入视频标题',
						trigger: 'blur'
					},
					sort: {
						required: true,
						message: '请选择视频分类',
						trigger: 'change'
					},
					thumbnail: {
						required: true,
						message: '请上传缩略图',
						trigger: 'change'
					},
					url: {
						required: true,
						message: '请上传视频',
						trigger: 'change'
					}
				}
			}
		},
		mounted() {
			this.getData()
			this.getSort()
			this.getMiniApp()
		},
		methods: {
			async getMiniApp() {
				const res = await this.$postForm('/admin/minis/getMiniApp')
				if (res.code == 1000) {
					this.vodSubAppid = res.data.vodSubAppid || ''
					this.vodId = res.data.id
				}
			},
			// 点击下载图片
			handleDownloadAppQrIMg() {
				// 这里是获取到的图片base64编码
				var name = this.$refs.appQrCodeUrl.name;
				var img = document.getElementById('code').getElementsByTagName('img')[0];
				const imgUrl = img.src;
				// 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
				if (window.navigator.msSaveOrOpenBlob) {
					let bstr = atob(imgUrl.split(',')[1]);
					let n = bstr.length;
					let u8arr = new Uint8Array(n);
					while (n--) {
						u8arr[n] = bstr.charCodeAt(n);
					}
					let blob = new Blob([u8arr]);
					window.navigator.msSaveOrOpenBlob(blob, name + '.' + 'png');
				} else {
					// 这里就按照chrome等新版浏览器来处理
					let a = document.createElement('a');
					a.href = imgUrl;
					a.setAttribute('download', name + '.' + 'png');
					a.click();
				}
			},
			// App二维码
			handleAppQrcode(row) {
				var vm = this;
				setTimeout(function() {
					vm.$refs.appQrCodeUrl.innerHTML = '';
					vm.$refs.appQrCodeUrl.name = row.id + "-" + row.title;
					var qrcode = new QRCode('code', {
						text: 'https://admin.shuatibang.com/h5/login.html?{"type":"video","id":"' + row.id +
							'","appid":"' + row.appid + '"}', // 需要转换为二维码的内容
						width: 150,
						height: 150,
						colorDark: '#000000',
						colorLight: '#ffffff',
						correctLevel: QRCode.CorrectLevel.H
					});
				}, 200);
			},
			// 点击查看二维码弹框
			lookQrcode(row) {
				var vm = this;
				this.qrcodeVisible = true;
				this.handleAppQrcode(row)
			},
			//获取选中的图片
			handleImgOk(data) {
				this.$set(this.form, 'thumbnail', data)
			},
			//点击图片库
			clickImg() {
				this.$refs.imgLibrary.show()
			},
			// 设置腾讯云点播
			async vodChange() {
				const res = await this.$post('/admin/minis/add', {
					id: this.vodId,
					vodSubAppid: this.vodSubAppid
				})
				this.$message.success('操作成功')
				this.tencentVisible = false
				this.getMiniApp()
			},
			handleUploadSuccess(res, file) {
				this.form.thumbnail = res.data
			},
			handleUploadVideoSuccess(res, file) {
				this.form.url = res.data
			},
			handlePageChange(val) {
				this.query.pageNumber = val
				this.getData();
			},
			handleSizeChange(val) {
				this.query.pageSize = val
				this.getData();
			},
			//新增修改
			submitQuestionVideo() {
				this.$refs['form'].validate(async (valid) => {
					if (valid) {
						this.form.videoType = 1
						const res = await this.$post('/admin/questionVideo/addQuestionVideo', this.form)
						if (res.code == 1000) {
							this.$message.success('提交成功')
							this.form = {}
							this.getData()
							this.editVisible = false
						} else {
							this.$message.error("录入失败")
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			// 点击上传时
			submitUpload() {
				if (this.fileList.length < 1) return this.$MessageBox('请先选取视频，再进行上传', '提示')
				this.uploadVideo()
			},
			// 文件列表改变时  将文件列表保存到本地
			handleChange(file, fileList) {
				this.fileList = fileList
			},
			// 自定义上传
			uploadVideo(e) {
				// 当
				if (this.fileList.length < 1) {
					window.alert('您还没有选取文件')
				} else {
					let that = this
					var url = URL.createObjectURL(this.fileList[0].raw);
					var audioElement = new Audio(url);
					audioElement.addEventListener("loadedmetadata",
						function() {
							that.form.duration = parseInt(audioElement.duration); //时长为秒
						});
					this.form.fileSize = this.fileList[0].raw.size / 1024 / 1024
					this.form.fileSize = this.form.fileSize.toFixed(2)
					//必须以函数的形式返回  sdk参数限制
					const getSignature = async () => {
						const data = await this.getVodSignature()
						console.log(data, "dataaa")
						return data
					}
					const tcVod = new TcVod({
						getSignature: getSignature // 获取上传签名的函数
					})
					// 获取通过elementui上传到本地的文件  因为参数类型必须为file 不能直接以对象的形式传输
					const mediaFile = this.fileList[0].raw
					const uploader = tcVod.upload({
						mediaFile: mediaFile
					})
					// 监听上传进度
					uploader.on('media_progress', info => {
						this.progress = parseInt(info.percent * 100)
					})
					// 上传结束时，将url存到本地
					uploader.done().then(doneResult => {
						// 保存地址
						this.form.fileId = doneResult.fileId
						this.$set(this.form, 'url', doneResult.video.url)
					})
				}
			},
			// 获取签名  这里的签名请求是由后端提供的，只需要拿到后端给的签名请求即可
			async getVodSignature() {
				let res = await this.$get('/admin/image/getSignature');
				return res.data;
			},
			//获取视频分类
			async getSort() {
				const res = await this.$get('/admin/questionVideo/getVideoSort', {
					pageNumber: 1,
					pageSize: 9999,
					type: 1
				})
				if (res.code == 1000) {
					this.sorts = res.data.list
				}
			},
			handleClose() {
				this.getSort()
			},
			handleSelectionChange(val) {
				this.multipleSelection = val
			},
			// 删除
			async handleDel(id) {
				const res = await this.$postForm('/admin/questionVideo/deleteQuestionVideo', {
					ids: id
				})
				if (res.code == 1000) {
					this.$message.success('删除成功')
					this.getData()
				}
			},
			//新增视频
			handleAdd(row) {
				if (row.id) {
					this.title = '编辑视频'
					this.form = JSON.parse(JSON.stringify(row))
				} else {
					this.title = '新增视频'
					this.form = {}
				}
				this.progress = 0
				this.editVisible = true
			},
			async getData() {
				this.query.status = 1
				this.query.videoType = 1
				const res = await this.$get('/admin/questionVideo/getVideo', this.query)
				if (res.code == 1000) {
					this.tableData = res.data.list
					this.pageTotal = res.data.totalRow
				}
			},
			handleSearch() {
				this.query.pageNumber = 1
				this.getData();
			},
			handleRefresh() {
				this.query = {
					pageNumber: 1,
					pageSize: 30
				}
				this.getData();
			}
		}
	}
</script>

<style scoped lang="scss">
	.upload_video /deep/ .el-upload {
		width: 100%;
		display: flex !important;
		flex-direction: column;
	}

	.upload_video /deep/ .el-button {
		width: 100px !important;
		margin-bottom: 10px !important;
	}
</style>